﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ERP.ERPSystem.ProductionSystem.Dto;
using ERP.Team.ProductionSystem;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ERP.ERPSystem.ProductionSystem
{
    /// <summary>
    /// 生产系统-生产管理-生产派单
    /// </summary>
    public class ProductionDispatchMainServices :ApplicationService, IProductionDispatchMainServices
    {
        private readonly IRepository<ProductionDispatchMain> _dispatchRepository;

        public ProductionDispatchMainServices(IRepository<ProductionDispatchMain> dispatchRepository)
        {
            _dispatchRepository = dispatchRepository;
        }

        /// <summary>
        /// 添加生产派单
        /// </summary>
        /// <param name="productionDispatchMainDto"></param>
        /// <returns></returns>
        public async Task<int> AddProductionDispatch(ProductionDispatchMainDto productionDispatchMainDto)
        {
            // 自动生成生产工单编号
            productionDispatchMainDto.ProductionWorkOrderCode = await GenerateWorkOrderCode();
            
            var adddispatch = ObjectMapper.Map<ProductionDispatchMainDto, ProductionDispatchMain>(productionDispatchMainDto);
            var result = await _dispatchRepository.InsertAsync(adddispatch);
            return result != null ? 1 : 0;
        }

        /// <summary>
        /// 显示生产派单
        /// </summary>
        /// <returns></returns>
        public async Task<List<ProductionDispatchMain>> GetProductionDispatch()
        {
            var dispatchlist=await _dispatchRepository.GetListAsync();
            return dispatchlist;
        }

        /// <summary>
        /// 获取指定前缀的工单数量
        /// </summary>
        /// <param name="prefix">前缀</param>
        /// <returns></returns>
        public async Task<int> GetWorkOrderCountByPrefix(string prefix)
        {
            var orders = await _dispatchRepository.GetListAsync(x => x.ProductionWorkOrderCode.StartsWith(prefix));
            return orders.Count;
        }

        /// <summary>
        /// 生成生产工单编号
        /// </summary>
        /// <returns></returns>
        private async Task<string> GenerateWorkOrderCode()
        {
            var today = DateTime.UtcNow; // 使用UTC时间避免时区问题
            var datePrefix = $"MO{today:yyyyMMdd}"; // 格式：MO20250120
            
            // 查询当天已有的工单数量
            var todayCount = await GetWorkOrderCountByPrefix(datePrefix);
            var nextNumber = todayCount + 1;
            
            // 生成4位序号，如：MO20250120001
            return $"{datePrefix}{nextNumber:D4}";
        }

        /// <summary>
        /// 更新派单人员
        /// </summary>
        /// <param name="id">派单ID</param>
        /// <param name="newOrderTarget">新的派单人员</param>
        /// <returns></returns>
        public async Task<int> UpdateOrderTarget(int id, string newOrderTarget)
        {
            var dispatch = await _dispatchRepository.FirstOrDefaultAsync(x => x.Id == id);
            if (dispatch != null)
            {
                dispatch.OrderTarget = newOrderTarget;
                await _dispatchRepository.UpdateAsync(dispatch);
                return 1;
            }
            return 0;
        }

        /// <summary>
        /// 批量更新派单人员
        /// </summary>
        /// <param name="ids">派单ID列表</param>
        /// <param name="newOrderTarget">新的派单人员</param>
        /// <returns></returns>
        public async Task<int> BatchUpdateOrderTarget(List<int> ids, string newOrderTarget)
        {
            var dispatches = await _dispatchRepository.GetListAsync(x => ids.Contains(x.Id));
            var updateCount = 0;
            
            foreach (var dispatch in dispatches)
            {
                dispatch.OrderTarget = newOrderTarget;
                await _dispatchRepository.UpdateAsync(dispatch);
                updateCount++;
            }
            
            return updateCount;
        }

        /// <summary>
        /// 根据ID获取生产派单信息
        /// </summary>
        /// <param name="id">派单ID</param>
        /// <returns></returns>
        public async Task<ProductionDispatchMain> GetProductionDispatchById(int id)
        {
            return await _dispatchRepository.FirstOrDefaultAsync(x => x.Id == id);
        }

        /// <summary>
        /// 更新生产派单信息
        /// </summary>
        /// <param name="id">派单ID</param>
        /// <param name="productionDispatchMainDto">更新的派单信息</param>
        /// <returns></returns>
        public async Task<int> UpdateProductionDispatch(int id, ProductionDispatchMainDto productionDispatchMainDto)
        {
            var dispatch = await _dispatchRepository.FirstOrDefaultAsync(x => x.Id == id);
            if (dispatch != null)
            {
                // 更新字段
                dispatch.WorkOrderName = productionDispatchMainDto.WorkOrderName;
                dispatch.TaskName = productionDispatchMainDto.TaskName;
                dispatch.WorkGroupName = productionDispatchMainDto.WorkGroupName;
                dispatch.DocumentStatus = productionDispatchMainDto.DocumentStatus;
                dispatch.ProductMaterialName = productionDispatchMainDto.ProductMaterialName;
                dispatch.ProductionStartTime = productionDispatchMainDto.ProductionStartTime;
                dispatch.ProductionEndTime = productionDispatchMainDto.ProductionEndTime;
                dispatch.OrderTarget = productionDispatchMainDto.OrderTarget;
                
                await _dispatchRepository.UpdateAsync(dispatch);
                return 1;
            }
            return 0;
        }

        /// <summary>
        /// 删除生产派单
        /// </summary>
        /// <param name="id">派单ID</param>
        /// <returns></returns>
        public async Task<int> DeleteProductionDispatch(int id)
        {
            var dispatch = await _dispatchRepository.FirstOrDefaultAsync(x => x.Id == id);
            if (dispatch != null)
            {
                await _dispatchRepository.DeleteAsync(dispatch);
                return 1;
            }
            return 0;
        }

        /// <summary>
        /// 批量删除生产派单
        /// </summary>
        /// <param name="ids">派单ID列表</param>
        /// <returns></returns>
        public async Task<int> BatchDeleteProductionDispatch(List<int> ids)
        {
            var dispatches = await _dispatchRepository.GetListAsync(x => ids.Contains(x.Id));
            var deleteCount = 0;
            
            foreach (var dispatch in dispatches)
            {
                await _dispatchRepository.DeleteAsync(dispatch);
                deleteCount++;
            }
            
            return deleteCount;
        }
    }
}
